package com.example.njupt.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.launcher.ARouter;
import com.example.njupt.MainActivity;
import com.example.njupt.R;
import com.example.njupt.constant.AppStatusConstant;
import com.example.njupt.helper.AppStatusHelper;
import com.example.njupt.views.toolbar.ToolbarHelper;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;

/**
 * Author:      mwang
 * Create Date: Created in 2021/4/23 9:34
 * Update Date:
 * Modified By:
 * Description: 基类BaseActivity
 */
public abstract class BaseActivity extends RxAppCompatActivity {

    private ToolbarHelper toolbarHelper;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        initAppStatus();
        initImmersive();
        setContentView(getLayoutId());
        screenRotate();
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
        initEventBus();
    }

    public ToolbarHelper getToolbarHelper() {
        provideToolbar();
        return toolbarHelper;
    }

    private void provideToolbar() {
        if (null == toolbarHelper) {
            Toolbar toolbar = findViewById(R.id.toolbar);
            if (null == toolbar) {
                throw new IllegalArgumentException("toolbar must included in layout file");
            }
            toolbarHelper = new ToolbarHelper(this, toolbar);
            //默认需要状态栏高度
            toolbarHelper.setImmersive(false);
        }
    }

    /**
     * 设置屏幕横竖屏切换
     * if true, set portrait, else, set landscape
     */
    private void screenRotate() {
        if (isScreenRotate()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    protected boolean isScreenRotate() {
        return true;
    }

    /**
     * 沉浸式体验
     * 当虚拟按键存在时，布局不会沉浸到虚拟按键部分
     * 当虚拟按键不存在时，布局沉浸全屏幕
     */

    private void initImmersive() {
        if (isImmerse()) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); //全屏显示

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWindow().setStatusBarColor(Color.TRANSPARENT);
                }
            } else {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明导航栏
            }
        }
    }

    protected boolean isImmerse() {
        return true;
    }

    /**
    *
    * */
    private static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    /**
     * 初始化eventBus
     */
    private void initEventBus() {
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    protected boolean useEventBus() {
        return false;
    }

    public void hideLoadingDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public void showLoadingDialog() {

        if (dialog == null) {
            dialog = new ProgressDialog(this);
        }
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 利用反射获取状态栏高度
     *
     * @return 返回状态栏的高度
     */
    public int getStatusBarHeight() {
        int result = 0;
        //获取状态栏高度的资源id
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 页面跳转
     *
     * @param clz 目标页面
     */
    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }

    /**
     * 携带数据的页面跳转
     *
     * @param clz    目标页面
     * @param bundle 数据
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 含有Bundle通过Class打开编辑界面
     *
     * @param clz         目标页面
     * @param bundle      数据
     * @param requestCode 自定义参数，用来判断从哪个activity中返回
     */
    public void startActivityForResult(Class<?> clz, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 检测应用状态
     */
    private void initAppStatus() {
        if (getAppStatus() == AppStatusConstant.STATUS_FORCE_KILLED) {
            protectApp();
        }
    }

    protected void protectApp() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_RESTART_APP);
        startActivity(intent);
    }

    private int getAppStatus() {
        return AppStatusHelper.getInstance().getAppStatus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.bind(this).unbind();
        if (useEventBus()) {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);//注销eventBus
            }
        }
    }

    /**
     * 获取布局Id
     */
    protected abstract int getLayoutId();

    /**
     * 初始化视图
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 初始化监听器
     */
    protected abstract void initListener();

}
